import Want from '@ohos.application.Want';
import AtManager from '@ohos.abilityAccessCtrl';
import ServiceExtension from '@ohos.application.ServiceExtensionAbility';
import ServiceExtensionContext from "D:/Work/HuaweiOHOS_SDK/OpenHarmonySDK_2022.12.07_fixed/9/ets/api/application/ServiceExtensionContext";
import rpc from '@ohos.rpc';

import {Logic} from '../model/Logic'
import {bluetooth} from '../Bluetooth/Bluetooth'

const TAG: string = "BtConnector[ServiceAbility]";
const version = 6
const REQUEST_CODE = 251 //'ы'

export default class ServiceAbility extends ServiceExtension {
  stub: any = null
  private atManager = AtManager.createAtManager()

  onCreate(want) {
    console.info(`${TAG} onCreate callUI service ver=${version}`);
    this.grantPermission()
    this.stub = new Stub("Bluetooth connection service", this.context);
    this.stub.start()
  }

  grantPermission() {
    console.info(`${TAG} grantPermission`)
    if (this.atManager === undefined) {
      console.info(`${TAG} grantPermission context undefined`)
    }
    // @ts-ignore
    else if (this.atManager.requestPermissionsFromUser === undefined) {
      console.info(`${TAG} grantPermission requestPermissionsFromUser undefined`)
    }
    try {
      // @ts-ignore
      this.atManager.requestPermissionsFromUser(this.context,
        ['ohos.permission.DISTRIBUTED_DATASYNC'])
        .then((result) => {
        console.log(`${TAG} grantPermission,requestPermissionsFromUser,result.requestCode=${result}`)
      }).catch ((err) => {
      console.log(`${TAG} grantPermission err1 is ${JSON.stringify(err)}`)
      })
    } catch (err) {
      console.log(`${TAG} grantPermission err1 is ${JSON.stringify(err)}`)
    }
    console.info(`${TAG} grantPermission end`)
  }

  onConnect(want: Want) {
    console.info(`${TAG} onConnect callUI service ver=${version}`);
    return this.stub
  }

  onDisconnect(want) {
    console.info(`${TAG} onDisconnect callUI service ver=${version}, want: ${want.abilityName}`);
  }

  onRequest(want: Want, startId: number) {
    console.info(`${TAG} onRequest callUI service`);
  }

  onDestroy() {
    console.info(`${TAG} onDestroy callUI service ver=${version}`);
    this.stub.stop()
  }
}

class Stub extends rpc.RemoteObject {
  private counter = 0
  private stopped = false
  private context: ServiceExtensionContext = null
  private logic: Logic = null

  constructor(descriptor, context:ServiceExtensionContext) {
    super(descriptor);
    this.context = context
    this.logic = new Logic(context, bluetooth, false)
  }

  start(){
    this.stopped = false
    this.logs()
    this.logic.start()
  }

  stop(){
    this.stopped = true
    this.logic.stop()
  }

  public logs(){
    if (this.stopped) return
    console.log(`${TAG} Servise worked ver=${version} count=${this.counter} ${this.context}`)
    this.counter++
    setTimeout(() => {this.logs()}, 5000)
  }

  onRemoteRequest(code, data, reply, option) {
    console.info(`${TAG} Stub onRemoteRequest ver=${version} code:` + code)
    if (code === REQUEST_CODE) {   // Чтоб никто не догадался
      let optFir = data.readInt();
      let optSec = data.readInt();
      reply.writeInt(optFir + optSec);
    }
    return true;
  }
}